<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tree Selector Mockup</title>

<style type="text/css">
@import "lib/dojotoolkit/dojo/resources/dojo.css";
@import "lib/dojotoolkit/dijit/themes/tundra/tundra.css";

body {
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
}

#debugPanel pre {
    font-family: "Lucida Console", "Courier New", Courier, monospace;

}

div.container {
    border: 1px solid green;
    margin: 10px;
}
</style>

<script type="text/javascript">
var djConfig = {
    isDebug: true,
    parseOnLoad: true,
    locale: "zh",
    extraLocale: ["en"]
};
</script>
<script type="text/javascript" src="lib/dojotoolkit/dojo/dojo.js"></script>
<script type="text/javascript">
    dojo.require("dojo.data.ItemFileReadStore");
    dojo.require("dojo.data.ItemFileWriteStore");
    dojo.require("dojo.date.locale");
    dojo.require("dojo.parser");

    dojo.require("dijit.Dialog");
    dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.form.ComboBox");
    dojo.require("dijit.form.Button");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dijit.form.FilteringSelect");
    dojo.require("dijit.form.RadioButton");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.TitlePane");

    dojo.require("dijit.tree.ForestStoreModel");
    dojo.require("dijit.tree.TreeStoreModel");
    dojo.require("dijit.Tree");
</script>
<script type="text/javascript">
function getDebugMsg() {
    var args = [];
    for (var i = 0; i< arguments.length; i += 1) {
        args.push(arguments[i]);
    }
    var msg = args.join(" ");
    return msg;
}

function debug(messages) {
    var msg = getDebugMsg.apply(null, arguments);
    console.debug(msg);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML = msg;
}

function append(messages) {
    var msg = getDebugMsg.apply(null, arguments);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML += "\n" + msg;
}

function show(id) {
    var element = dojo.byId(id);
    if (element.style.display === "none") {
        element.style.display = "";
    }
}

function hide(id) {
    var element = dojo.byId(id);
    element.style.display = "none";
}
</script>
<style type="text/css">
@import "css/rounded-button.css";
@import "css/rounded-corners.css";

body {
    padding: 10px;
}

.TreeComboBoxPopUp {
    min-width: 100px;
    min-height: 50px;
    max-width: 400px;
    max-height: 400px;
    overflow: auto;
    border: 1px solid black;
}

.tundra .dijitTreeNodeSelected .dijitTreeLabel {
/*
    background-color: #BEEBFF;
    background-color: #E7F4F9;
*/
    background-color: #3559ac;
    color: white;
}

.tundra .dijitTreeNodeHover {
    /*background-image: none;
    background-color: #3559ac;
    color: white;*/
}
</style>
<script type="text/javascript">
dojo.addOnLoad(function() {
    debug("loaded");

    var productGroupSelector = dijit.byId("productGroupSelector");
    var parentSelector = dijit.byId("parentSelector");
    var tree = dijit.byId("tree");
    var store = tree.model.store;

    var reloadParentSelector = function(items) {
        parentSelector.reset();
        parentSelector.attr("query", null);

        var ids = [];
        dojo.forEach(items, function(item) {
            var id = store.getIdentity(item);
            ids.push(id);
        });
        var pattern = ids.join("|");
        var regExp = new RegExp(pattern, "mi");
        var query = {
            id: pattern
        };
        parentSelector.attr("query", query);
        append("parent:", regExp.source);
    };

    dojo.connect(productGroupSelector, "onChange", function(value) {
        var name = value;

        store.fetch({
            query: {name: name},
            onComplete: function(items) {
                var item = items[0];
                loadParentItems(store, item, reloadParentSelector);
            }
        });
    });

    dojo.connect(tree, "onClick", function(item) {
        var store = tree.model.store;

       // var item = treeNode.item;
        var name = store.getValue(item, "name");
        debug("tree selected item:", name);

        productGroupSelector.attr("value", name);
    });

});

function changeModel(treeModel, showRoot) {

    var tree = dijit.byId("tree");

    tree.destroy();

    tree = new dijit.Tree({
        id: "tree",
        model: treeModel,
        showRoot: showRoot,
        persist: false
    });
    dojo.byId("container").appendChild(tree.domNode);
    tree.startup();
}

function focusNode(path) {
    var tree = dijit.byId("tree");
    var selector = dijit.byId("productGroupSelector");

    if (!dojo.isArray(path)) {
        path = [].push(path);
    }

    var length = path.length;
    var identity = path[length-1];

    var item = tree.model.store._getItemByIdentity(identity);
    if (item) {
        //tree.attr("selectedItem", item);
        selector.attr("item", item);
    }
    tree.attr("path", path);
}

function selectParent() {
    var parentSelector = dijit.byId("parentSelector");
    var item = parentSelector.attr("item");
    var tree = dijit.byId("tree");
    tree.attr("selectedItem", item);
}

function loadParentItems(store, item, callback) {
    var parentItems = store.getValues(item, "parents");

    var results = [];
    if (parentItems.length < 1) {
        callback.call(null, results);
    }

    for (var i = 0; i < parentItems.length; i+=1) {
        var parentItem = parentItems[i];

        if(!store.isItemLoaded(parentItem)){
            store.loadItem({
                item: parentItem,
                onItem: function(item) {
                    results.push(item);
                    if (i === parentItems.length - 1) {
                        callback.call(null, results);
                    }
                },
                onError: function() {
                    console.warn("error loading parent item");
                }
            });
        } else {
            results.push(parentItem);
            if (i === parentItems.length - 1) {
                callback.call(null, results);
            }
        }
    }
}


</script>
</head>
<body class="tundra">

  <!-- Debug Panel -->
  <div dojoType="dojo.dnd.Moveable">
    <div id="debugPanel" dojoType="dijit.TitlePane" title="Debug Panel" style="">
      <pre id="debugPanelContent"></pre>
    </div>
  </div>
  <hr />

  <div id="main" class="container">
    <div dojoType="dojo.data.ItemFileReadStore" jsId="nodeStore" url="./data/tree.json"></div>
    <div dojoType="dojo.data.ItemFileWriteStore" jsId="countryStore" url="./data/countries.json"></div>
    <div dojoType="dojo.data.ItemFileWriteStore" jsId="productGroupStore" url="./data/tree-multiple_parent.json"></div>
    <div dojoType="dojo.data.ItemFileWriteStore" jsId="productGroupStore_tree" url="./data/product_group_tree.json"></div>
    <div dojoType="dojo.data.ItemFileWriteStore" jsId="productGroupStore_flat" url="./data/product_groups.json"></div>

    <div dojoType="dijit.tree.ForestStoreModel" jsId="productGroupModel" store="productGroupStore" rootId="$root$" rootLabel="ROOT" childrenAttrs="children" deferItemLoadingUntilExpand="true" query="{type:'root'}"></div>
    <div dojoType="dijit.tree.TreeStoreModel" jsId="treeModel" store="productGroupStore_tree" childrenAttrs="children" deferItemLoadingUntilExpand="true" query="{type:'root'}"></div>
    <div dojoType="dijit.tree.ForestStoreModel" jsId="forestModel" store="productGroupStore_flat" rootId="$root$" rootLabel="ROOT" childrenAttrs="children" deferItemLoadingUntilExpand="true" query="{type:'group'}"></div>

    <!-- ComboBox -->
    <div dojoType="dojo.dnd.Moveable">
      <div dojoType="dijit.TitlePane" title="ComboBox" style="">
        <label for="productGroupSelector">Product groups:</label> <input id="productGroupSelector" dojoType="dijit.form.ComboBox" value="---- Select a product group ----" store="productGroupStore" searchAttr="name" query="{type:'item'}" style="width: 300px;" />
        &nbsp;
        <label for="parentSelector">Parents:</label> <input id="parentSelector" dojoType="dijit.form.ComboBox" value="---- Select a parent ----" store="productGroupStore" searchAttr="name" query="{type: 'group'}" />
        <a href="javascript://" onclick="selectParent();">focus parent</a>
      </div>
    </div>
    <!-- Tree -->
    <div id="container" class="TreeComboBoxPopUp">
      <div id="tree" dojoType="dijit.Tree" model="productGroupModel" showRoot="false" persist="false"></div>
    </div>
    <hr />

    <div dojoType="dijit.form.Button" onClick="changeModel(forestModel, false);">Show in Forest mode</div>
    <div dojoType="dijit.form.Button" onClick="changeModel(treeModel, true);">Show in Tree mode</div>
    <div dojoType="dijit.form.Button" onClick="focusNode(['$root$', 'Software Group (SWG)', 'EBLInformation_ManagementCY']);">focus Information Management</div>
    <div dojoType="dijit.form.Button" onClick="focusNode(['$root$', 'Rational', 'EB3JazzNA']);">focus Jazz</div>


  </div>
</body>
</html>
